import Stomp from "stompjs";
import {
  MQTT_SERVICE,
  MQTT_USERNAME,
  MQTT_PASSWORD,
  MQTT_TOPIC,
} from "@/utils/mqtt";

const state  = {
    client: null,
    isConnect: false, // 是否连接
}

const mutations = {
    INIT_CONNECT: (state) => {
        state.client = Stomp.client(MQTT_SERVICE)
    },
    SET_CONNECT: (state, connect) => {
        state.isConncet = connect
    },
    
}

const actions = {
    onConnected({commit,state}) {
        commit('SET_CONNECT',true)
        console.log('连接成功')
        //订阅的频道
        state.client.subscribe(MQTT_TOPIC, 
            (msg) => {
            //接收消息的处理
            console.log("订阅成功");
            const data = JSON.parse(msg.body)
            // 注册通知
            if(data.type === 'register') {
                Vue.prototype.$notify.success({
                title: data.body.title,
                message: data.body.desc,
                duration: 0
                });
            }
        }, 
        () => {
            dispatch('onFailed')
        });
    },
      onFailed({commit,dispatch},msg) {
        console.log('连接失败')
        commit('SET_CONNECT',false)
        dispatch('onPollConnect')
      },
      //成功时的回调函数
      responseCallback(msg) {
        //接收消息的处理
        console.log("订阅成功");
        const data = JSON.parse(msg.body)
          // 注册通知
          if(data.type === 'register') {
            Vue.prototype.$notify.success({
              title: data.body.title,
              message: data.body.desc,
              duration: 0
            });
          }
      },
      //连接
      connect({commit,dispatch,state}) {
        if(state.isConncet) return
        commit('INIT_CONNECT')
        return new Promise((resolve,reject) => {
          state.client.connect(
            MQTT_USERNAME, 
            MQTT_PASSWORD, 
            () => {
                dispatch('onConnected')
                resolve(true)
            }, 
            () => {
                dispatch('onFailed')
                reject(false)
            });
          state.client.debug = null
        })
      },
      // 断开
      onClose({commit,dispatch,state},isResetConnect = true) {
        state.client.disconnect(() => {
          commit('SET_CONNECT',false)
          console.log('已关闭连接')
          if(isResetConnect) {
            dispatch('connect')
            console.log('已断开---尝试重连')
          }
        })
      },
      // 轮询重连
      onPollConnect({dispatch,state}) {
        dispatch('onClose')
        // 每5秒发起连接
        let timeId = setInterval(() => {
          if(state.isConnect) {
            clearInterval(timeId)
            return
          }
        },5000)
      }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}